import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/constants.dart';

/// 播放控制组件
/// 提供播放、暂停、上一首、下一首等控制功能
class PlayControls extends StatefulWidget {
  final double iconSize;
  final bool showShuffle;
  final bool showRepeat;
  final Color? iconColor;
  final Color? activeColor;

  const PlayControls({
    super.key,
    this.iconSize = AppTheme.iconSizeLarge,
    this.showShuffle = true,
    this.showRepeat = true,
    this.iconColor,
    this.activeColor,
  });

  @override
  State<PlayControls> createState() => _PlayControlsState();
}

class _PlayControlsState extends State<PlayControls>
    with TickerProviderStateMixin {
  late AnimationController _playButtonController;
  late AnimationController _scaleController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _initAnimations();
  }

  /// 初始化动画
  void _initAnimations() {
    _playButtonController = AnimationController(
      duration: AppTheme.animationDurationFast,
      vsync: this,
    );
    
    _scaleController = AnimationController(
      duration: AppTheme.animationDurationFast,
      vsync: this,
    );
    
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.9,
    ).animate(CurvedAnimation(
      parent: _scaleController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _playButtonController.dispose();
    _scaleController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AudioPlayerService>(
      builder: (context, audioService, child) {
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            // 随机播放按钮
            if (widget.showShuffle)
              _buildControlButton(
                icon: Icons.shuffle,
                isActive: audioService.playMode == PlayMode.shuffle,
                onPressed: () => _toggleShuffle(audioService),
              ),
            
            // 上一首按钮
            _buildControlButton(
              icon: Icons.skip_previous,
              isActive: false,
              onPressed: audioService.hasPrevious
                  ? () => _playPrevious(audioService)
                  : null,
            ),
            
            // 播放/暂停按钮
            _buildPlayPauseButton(audioService),
            
            // 下一首按钮
            _buildControlButton(
              icon: Icons.skip_next,
              isActive: false,
              onPressed: audioService.hasNext
                  ? () => _playNext(audioService)
                  : null,
            ),
            
            // 循环播放按钮
            if (widget.showRepeat)
              _buildRepeatButton(audioService),
          ],
        );
      },
    );
  }

  /// 构建控制按钮
  Widget _buildControlButton({
    required IconData icon,
    required bool isActive,
    required VoidCallback? onPressed,
  }) {
    final iconColor = widget.iconColor ?? AppTheme.textPrimaryDark;
    final activeColor = widget.activeColor ?? AppTheme.primaryColor;
    
    return GestureDetector(
      onTapDown: onPressed != null ? (_) => _scaleController.forward() : null,
      onTapUp: onPressed != null ? (_) => _scaleController.reverse() : null,
      onTapCancel: onPressed != null ? () => _scaleController.reverse() : null,
      onTap: onPressed,
      child: ScaleTransition(
        scale: _scaleAnimation,
        child: Container(
          width: widget.iconSize + 16,
          height: widget.iconSize + 16,
          decoration: BoxDecoration(
            color: isActive
                ? activeColor.withOpacity(0.2)
                : Colors.transparent,
            borderRadius: BorderRadius.circular((widget.iconSize + 16) / 2),
          ),
          child: Icon(
            icon,
            size: widget.iconSize * 0.8,
            color: onPressed == null
                ? iconColor.withOpacity(0.3)
                : isActive
                    ? activeColor
                    : iconColor,
          ),
        ),
      ),
    );
  }

  /// 构建播放/暂停按钮
  Widget _buildPlayPauseButton(AudioPlayerService audioService) {
    final iconColor = widget.iconColor ?? AppTheme.textPrimaryDark;
    
    return GestureDetector(
      onTapDown: (_) {
        _scaleController.forward();
        _playButtonController.forward();
      },
      onTapUp: (_) {
        _scaleController.reverse();
        _playButtonController.reverse();
      },
      onTapCancel: () {
        _scaleController.reverse();
        _playButtonController.reverse();
      },
      onTap: () => _togglePlayPause(audioService),
      child: ScaleTransition(
        scale: _scaleAnimation,
        child: Container(
          width: widget.iconSize + 24,
          height: widget.iconSize + 24,
          decoration: BoxDecoration(
            gradient: audioService.currentMusic != null
                ? AppTheme.primaryGradient
                : null,
            color: audioService.currentMusic == null
                ? iconColor.withOpacity(0.2)
                : null,
            borderRadius: BorderRadius.circular((widget.iconSize + 24) / 2),
            boxShadow: audioService.currentMusic != null
                ? AppTheme.elevatedShadow
                : null,
          ),
          child: AnimatedSwitcher(
            duration: AppTheme.animationDurationFast,
            child: Icon(
              audioService.isPlaying ? Icons.pause : Icons.play_arrow,
              key: ValueKey(audioService.isPlaying),
              size: widget.iconSize,
              color: audioService.currentMusic != null
                  ? Colors.white
                  : iconColor.withOpacity(0.5),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建循环播放按钮
  Widget _buildRepeatButton(AudioPlayerService audioService) {
    IconData icon;
    bool isActive;
    
    switch (audioService.playMode) {
      case PlayMode.repeatAll:
        icon = Icons.repeat;
        isActive = true;
        break;
      case PlayMode.repeatOne:
        icon = Icons.repeat_one;
        isActive = true;
        break;
      default:
        icon = Icons.repeat;
        isActive = false;
        break;
    }
    
    return _buildControlButton(
      icon: icon,
      isActive: isActive,
      onPressed: () => _toggleRepeat(audioService),
    );
  }

  /// 切换播放/暂停
  void _togglePlayPause(AudioPlayerService audioService) {
    if (audioService.currentMusic == null) {
      // 如果没有当前音乐，尝试播放第一首
      _playFirstAvailableMusic(audioService);
      return;
    }
    
    if (audioService.isPlaying) {
      audioService.pause();
    } else {
      audioService.resume();
    }
  }

  /// 播放第一首可用音乐
  void _playFirstAvailableMusic(AudioPlayerService audioService) async {
    try {
      final musicLibraryService = Provider.of<MusicLibraryService>(
        context,
        listen: false,
      );
      
      final musicList = await musicLibraryService.getAllMusic();
      if (musicList.isNotEmpty) {
        audioService.setPlaylist(musicList);
        audioService.play();
      } else {
        _showMessage('音乐库为空，请先扫描音乐文件');
      }
    } catch (e) {
      _showMessage('播放失败: $e');
    }
  }

  /// 播放上一首
  void _playPrevious(AudioPlayerService audioService) {
    audioService.playPrevious();
  }

  /// 播放下一首
  void _playNext(AudioPlayerService audioService) {
    audioService.playNext();
  }

  /// 切换随机播放
  void _toggleShuffle(AudioPlayerService audioService) {
    if (audioService.playMode == PlayMode.shuffle) {
      audioService.setPlayMode(PlayMode.sequence);
    } else {
      audioService.setPlayMode(PlayMode.shuffle);
    }
  }

  /// 切换循环播放
  void _toggleRepeat(AudioPlayerService audioService) {
    switch (audioService.playMode) {
      case PlayMode.sequence:
      case PlayMode.shuffle:
        audioService.setPlayMode(PlayMode.repeatAll);
        break;
      case PlayMode.repeatAll:
        audioService.setPlayMode(PlayMode.repeatOne);
        break;
      case PlayMode.repeatOne:
        audioService.setPlayMode(PlayMode.sequence);
        break;
    }
  }

  /// 显示消息
  void _showMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.warningColor,
        duration: const Duration(seconds: 2),
      ),
    );
  }
}

/// 迷你播放控制组件
/// 用于在其他页面显示简化的播放控制
class MiniPlayControls extends StatelessWidget {
  final double iconSize;
  final Color? iconColor;
  final Color? activeColor;

  const MiniPlayControls({
    super.key,
    this.iconSize = AppTheme.iconSizeMedium,
    this.iconColor,
    this.activeColor,
  });

  @override
  Widget build(BuildContext context) {
    return PlayControls(
      iconSize: iconSize,
      showShuffle: false,
      showRepeat: false,
      iconColor: iconColor,
      activeColor: activeColor,
    );
  }
}